package com.gwtplatform.samples.basic.client.main;

import com.google.inject.Inject;

import com.guit.client.GuitPresenter;
import com.guit.client.binder.GuitBinder;
import com.guit.client.binder.ViewField;
import com.guit.client.binder.ViewHandler;
import com.guit.client.place.Place;
import com.guit.client.place.PlaceName;
import com.gwtplatform.samples.basic.client.HasInnerText;
import com.gwtplatform.samples.basic.client.TextBoxI;
import com.gwtplatform.samples.basic.client.attacher.RootPanelAttacher;
import com.gwtplatform.samples.basic.client.main.MainPresenter.MainBinder;
import com.gwtplatform.samples.basic.client.response.ResponsePresenter;
import com.gwtplatform.samples.basic.shared.FieldVerifier;

@PlaceName("main")
public class MainPresenter extends GuitPresenter<MainBinder> implements Place<Void> {

    public static interface MainBinder extends GuitBinder<MainPresenter> {
    }

    private final RootPanelAttacher attacher;

    @ViewField
    HasInnerText error;
    
    @ViewField
    TextBoxI name;
    
    @Inject
    public MainPresenter(RootPanelAttacher attacher) {
        this.attacher = attacher;
    }
    
    /**
     * Send the name from the nameField to the server and wait for a response.
     */
    @ViewHandler
    protected void send$click() {
        // First, we validate the input.
        error.setInnerText("");
        if (!FieldVerifier.isValidName(name.getText())) {
            error.setInnerText("Please enter at least four characters");
            return;
        }

        placeManager.go(ResponsePresenter.class, name.getText());
    }

    @Override
    public void go(Void data) {
        attacher.attach(getView());
        name.setFocus(true);
        name.selectAll();
    }
}
